/**
 * 通用方法
 */
const app = getApp();

var utils = require('./util.js');
// #ifdef APP-PLUS|| MP
const permissionSet = require('@/utils/checkpermission.js');
// #endif
function jsonSort(jsonObj) {
	let arr = [];

	for (var key in jsonObj) {
		arr.push(key);
	}

	arr.sort();
	let str = '';

	for (var i in arr) {
		str += arr[i] + '=' + jsonObj[arr[i]] + '&';
	}

	return str.substr(0, str.length - 1);
}
/**
 * ajax封装
 * @param url  请求链接
 * @param data 请求参数
 * @param success    回调函数
 * @param fail    回调函数
 * @param complete    回调函数
 */

function _ajax(url, data, success, fail, complete) {
	// 自动补全域名
	if (url.indexOf('/') == 0) {
		url = app.globalData.web_url + url;
	}

	var token = uni.getStorageSync('token') || '';
	uni.request({
		url: url,
		data: data,
		sslVerify: false,
		header: {
			'content-type': 'application/x-www-form-urlencoded',
			TOKEN: token
		},
		method: 'POST',
		dataType: 'json',
		success: function(res) {
			// console.log(res);
			if (res.data.code === 401) {
				// 需要登录，清除默认存储的token
				uni.setStorageSync('token', '');
				checkLogin(function(ret) {
					if (ret) {
						_ajax(url, data, success, fail, complete);
					} else {
						showError(res.data.msg, function() {
							fail && fail(res);
						});
					}
				});
				return false;
			} else if (res.data.code === 0) {
				if (typeof fail == 'function') {
					return fail(res);
				}
				// showError(res.data.msg);
				return false;
			}

			success && success(res.data);

			if (res.data && res.data.msg) {
				toast(res.data.msg);
			}
		},
		fail: function(res) {
			showError(res.errMsg, function() {
				fail && fail(res);
			});
		},
		complete: function(res) {
			uni.hideNavigationBarLoading();
			complete && complete(res);
		}
	});
	return false;
}
/**
 * 检查登录状态
 * @param cb    回调函数
 */

function checkLogin(cb) {
	if (uni.getStorageSync('token')) {
		typeof cb == 'function' && cb(true);
	} else {
		uni.showModal({
			title: '提示',
			content: '是否去登录',
			success: function (res) {
				if (res.confirm) {
					uni.navigateTo({
						url: '/pages/home/login/login'
					})
				} else if (res.cancel) {
					console.log('用户点击取消');
				}
			}
		});

	}
}

function checkUpdate(is_click) {

	//获取当前app版本信息
	plus.runtime.getProperty(plus.runtime.appid, function(widgetInfo) {
		var version = widgetInfo.version;


		var platform = plus.os.name;
		if (plus.os.name == 'Android') {
			platform = 'android';
		} else if (plus.os.name == 'iOS') {
			platform = 'ios';
		}
		console.log(platform)
		getAjaxData('/api/xiluhouse.common/check_version', {
			version: version,
			platform: platform
		}, function(res) {




			if (res.code == 1) {
				if (res.data.newversion) {
					plus.nativeUI.confirm("检测到有新版本，是否更新", function(e) {
						if (e.index == 0) {
							if (plus.networkinfo.getCurrentType() != 3) {
								plus.nativeUI.confirm("检测到您目前非Wifi连接，是否继续更新",
									function(e) {
										if (e.index == 0) {

											downWgt(res.data.downloadurl);
										} else {

										}
									}, "", )["取消", "确定"]
								return;
							}
							downWgt(res.data.downloadurl); //下载文件
						} else {
							//plus.runtime.quit();//安卓控制不更新退出应用

						}
					}, "", ["立即更新", "以后再说"]);

					//dtask.start();
				}

			} else {
				return false;

			}

		}, function(res) {

			if (is_click) {


				showError(res.data.msg);
			}
			return false;
		});




	});


}

function downWgt(url) {

	plus.nativeUI.showWaiting("正在更新，请耐心等待...");
	uni.downloadFile({ //执行下载
		url: url, //下载地址
		success: downloadResult => { //下载成功
			uni.hideLoading();
			if (downloadResult.statusCode == 200) {
				plus.runtime.install( //安装
					downloadResult.tempFilePath, {
						force: true
					},

				);
			}
		}
	});
}

function afterLogin(userinfo) {
	uni.setStorageSync('token', userinfo.token);
	uni.setStorageSync('mobile', userinfo.mobile);
	uni.setStorageSync('userInfo', userinfo);
	app.globalData.chat_config.url = app.globalData.ws_domain + '?token=' + uni.getStorageSync('token');
	app.ConnectSocket();
	app.globalData.userInfo = userinfo;
}

function showError(msg, callback) {
	uni.showModal({
		title: '温馨提示',
		content: msg,
		showCancel: false,
		success: function(res) {
			callback && callback();
		}
	});
}

function showSuccess(msg, callback) {
	uni.showToast({
		title: msg,
		icon: 'success',
		mask: true,
		success: function() {
			callback &&
				setTimeout(function() {
					callback();
				}, 1500);
		}
	});
}

function toast(msg) {
	uni.showToast({
		title: msg,
		icon: 'none'
	});
}
/**
 * post 请求接口 分页列表
 */

function getAjaxList(that, url, data, success, fail, complete) {
	if (that.is_ajax_list) {
		return false;
	}

	that.is_ajax_list = true;

	_ajax(url, data, success, fail, function(res) {
		that.is_ajax_list = false;
		that.loadStatus = 'loadmore';
		complete && complete(res);
	});
}
/**
 * post 请求接口数据
 */

function getAjaxData(url, data, success, fail, complete) {
	_ajax(url, data, success, fail, complete);
}
/**
 * post 表单提交
 */

function submitAjaxData(that, url, data, success, fail, complete) {
	//按钮状态
	if (that.btnStatus) {
		return false;
	}
	that.btnStatus = true;
	// uni.showLoading({
	// 	title: '提交中...'
	// });uni.hideLoading();

	_ajax(url, data, success, fail, function(res) {
		that.btnStatus = false;
		complete && complete(res);
	});
}
/**
 * 带参跳转到tab页面
 */
function jumpPages(url) {
	var param = {};

	if (url.indexOf('?') != -1) {
		var i = url.indexOf('?');
		var str = url.substring(i + 1);
		var searchArr = str.split('&');

		for (var i in searchArr) {
			param[searchArr[i].split('=')[0]] = searchArr[i].split('=')[1];
		}
	}

	app.globalData.pagesParam = param;
	app.globalData.is_need_page_change = true;
	uni.switchTab({
		url: url
	});
}
// 保存图片
function saveImages(filePath) {
	// #ifdef APP-PLUS|| MP
	permissionSet.checkPermission('photoLibraryRead', function() {
		startSaveImages(filePath);
	})
	return false;
	// #endif
}

function startSaveImages(filePath) {
	uni.saveImageToPhotosAlbum({
		filePath: filePath,
		success: function() {
			uni.showToast({
				icon: "success",
				title: "保存成功"
			})
		}
	});
}
//上传图片

var tempFilePaths;
var callback;

function chooseImg(num, cb) {
	// #ifdef APP-PLUS|| MP
	permissionSet.checkPermission('camera', function() {
		permissionSet.checkPermission('photoLibraryRead', function() {
			startChooseImg(num, cb);
		})
	})
	return false;
	// #endif
	startChooseImg(num, cb);
}

function startChooseImg(num, cb) {
	num = num || 9;
	callback = cb || '';
	uni.chooseImage({
		count: num,
		// 默认9
		// sizeType: ['original', 'compressed'],
		// 可以指定是原图还是压缩图，默认二者都有
		sourceType: ['album', 'camera'],
		// 可以指定来源是相册还是相机，默认二者都有
		success: function(res) {
			console.log(res);
			// 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
			tempFilePaths = res.tempFilePaths;
			var tempFiles = res.tempFiles;
			for(var i=0;i<tempFilePaths.length;i++){
				//#ifdef H5
				blobToFile(tempFilePaths[i],tempFilePaths.length-i);
				//#endif
				//#ifndef H5
				uploadImg(tempFilePaths[i],tempFilePaths.length-i);
				//#endif
			}


		}
	});
}

function uploadImg(tempFile,remain_num) {
	var url = app.globalData.web_url + '/api/xiluhouse/common/upload';
	uni.showLoading({
		title: '上传中...'
	});
	var token = uni.getStorageSync('token') || '';
	uni.uploadFile({
		url: url,
		filePath: tempFile,
		name: 'file',
		header: {
			'content-type': 'application/x-www-form-urlencoded',
			TOKEN: token,
		},
		success: function(res) {
			var ret = JSON.parse(res.data);

			if (ret.code == 1) {
				typeof callback == 'function' && callback(ret.data); //图片上传成功后置操作
				if (remain_num <=1) {
					uni.hideLoading();
				}
			} else {
				showError(ret.msg);
				uni.hideLoading();
			}
		},
		fail: function(res) {
			uni.hideLoading();
		}
	});
}
function blobToFile(path, remain_num) {
	var url = app.globalData.web_url + '/api/xiluhouse/common/upload';
	//#ifdef H5
	//blob: 地址转为data url格式，否则php获取不到
	let xhr = new XMLHttpRequest;
	xhr.responseType = 'blob';
	 var token = uni.getStorageSync('token') || '';
	xhr.onload = () => {
		let recoveredBlob = xhr.response;
		let reader = new FileReader;
		reader.onload = () => {
			let blobAsDataUrl = reader.result;
			//上传图像
			uni.request({
				method: 'POST',
				url: url,
				data: {
					basedata: blobAsDataUrl
				},
				header: {
					TOKEN: token,
				},
				success: (res) => {
					var ret = res.data;
					if (ret.code == 1) {
						typeof callback == 'function' && callback(ret.data); //图片上传成功后置操作
						if (remain_num <=1) {
							uni.hideLoading();
						}
					} else {
						showError(ret.msg);
						uni.hideLoading();
					}
				},
				fail: (e) => {
					uni.hideLoading();
				}
			});
		};
		reader.readAsDataURL(recoveredBlob);
	};
	xhr.open('GET', path);
	xhr.send();
	//#endif
}

function formatNumber(n) {
	n = n.toString();
	return n[1] ? n : '0' + n;
}
/**
 * 时间戳转化为年 月 日 时 分 秒
 * number: 传入时间戳
 * format：返回格式，支持自定义，但参数必须与formateArr里保持一致
 */

function formatTime(number, format = 'Y-M-D') {
	var formateArr = ['Y', 'M', 'D', 'h', 'm', 's'];
	var returnArr = [];
	var date = new Date(number * 1000);
	returnArr.push(date.getFullYear());
	returnArr.push(formatNumber(date.getMonth() + 1));
	returnArr.push(formatNumber(date.getDate()));
	returnArr.push(formatNumber(date.getHours()));
	returnArr.push(formatNumber(date.getMinutes()));
	returnArr.push(formatNumber(date.getSeconds()));

	for (var i in returnArr) {
		format = format.replace(formateArr[i], returnArr[i]);
	}

	return format;
}

function judgeNetworkStatus(callback) {
	uni.getNetworkType({
		success(res) {
			const networkType = res.networkType;
			console.log(res);
			callback(networkType); // if ("none" == networkType) {
			//   wx.showLoading({
			//     title: '网络连接失败',
			//     mask: true
			//   })
			//   judgeNetworkStatus(callback);
			// } else {
			//   wx.hideLoading()
			//   callback(networkType)
			// }
		},

		fail(err) {
			console.log(err);
		},

		complete(cpe) {
			console.log(cpe);
		}
	});
}
/**
 * 跳转聊天页面
 */
function jumpToChat(user_id = 0, house_id = 0,house_type="building") {
	if (user_id == 0) {
		user_id = app.globalData.config.service_user_id;
		if (!user_id) {
			toast('未配置客服，无法与客服聊天');
			return false;
		}
	}
	uni.navigateTo({
		url: '/pages/chat/chat/chat?receive_user_id=' + user_id+ '&house_type='+ house_type + '&house_id=' + house_id,
	})
}
/**
 * 做任务
 */
function dotask(that, type) {
	if (!uni.getStorageSync('token')) {
		return false;
	}
	var task_id = 0;
	var taskData = app.globalData.taskData;
	taskData.forEach((element) => {
		if (element.type == type) {
			task_id = element.id
		}
	});
	if (!task_id) {
		return false;
	}
	submitAjaxData(
		that,
		'/api/xiluhouse/score/dotask', {
			task_id: task_id
		}
	);
}
/**
 * 跳转广告
 * @param {*} that
 * @param {*} param
 */

function jumpAdvertTo(that, param) {
	if (param.goto_type == 1) {
		return false;
	} // $goto_type  - 跳转方式:1=不跳转,2=跳转外链,3=跳转内链,4=我要订阅

	if (param.goto_type == 4) {
		// 我要订阅
		// 处理手机号码
		var appoint_mobile = uni.getStorageSync('mobile') || that.data.appoint_mobile;
		that.broker_user_id = 0;
		that.appoint_mobile = appoint_mobile;
		that.popupStatus = false;
		that.appoint_type = 1;
		that.appoint_subscribe_type = 3;
		that.submitAppointLog();
	} else if (param.goto_type == 2) {
		uni.navigateTo({
			url: '/pages/home/webview/webview?url=' + param.goto_url
		});
	} else if (param.goto_type == 5) {
		uni.navigateTo({
			url: '/pages/home/webview/webview?url=' + param.goto_url
		});
	} else if (param.goto_type == 3) {
		var redirectArr = ['/pages/home/index/index', '/pages/home/building_list/building_list',
			'/pages/home/information/information', '/pages/home/personal/personal'
		];

		if (param.insidepages.is_need_login == 2) {
			app.globalData.nowThat = that;
			checkLogin(function(ret) {
				if (ret) {
					if (redirectArr.indexOf(param.insidepages.wxmini_url) == -1) {
						if (param.insidepages.is_need_param == 2) {
							uni.navigateTo({
								url: param.insidepages.wxmini_url + '?id=' + param.goto_param
							});
						} else {
							uni.navigateTo({
								url: param.insidepages.wxmini_url
							});
						}
					} else {
						uni.switchTab({
							url: param.insidepages.wxmini_url
						});
					}
				} else {
					functions.toast('请先登录');
				}
			});
		} else {
			if (redirectArr.indexOf(param.insidepages.wxmini_url) == -1) {
				if (param.insidepages.is_need_param == 2) {
					uni.navigateTo({
						url: param.insidepages.wxmini_url + '?id=' + param.goto_param
					});
				} else {
					uni.navigateTo({
						url: param.insidepages.wxmini_url
					});
				}
			} else {
				uni.switchTab({
					url: param.insidepages.wxmini_url
				});
			}
		}
	}
}

// 处理绑定上级id
function handlePid(scenetitle = '', options, cb) {
	var id = 0;
	var pid = 0;
	if (options.scene) {
		var scene = decodeURIComponent(options.scene);
		if (scenetitle) {
			if (scene.indexOf('%2C') != -1) {
				scene = scene.replace('%2C', ',');
			}
			var temp_arr = scene.split(',');
			if (temp_arr.length == 2) {
				var str1 = temp_arr[0];
				var str2 = temp_arr[1];
				var arr2 = str2.split('_');
				if (arr2.length == 2 && arr2[0] == scenetitle) {
					id = arr2[1];
				}
				var arr = str1.split('_');
				if (arr.length == 2) {
					pid = arr[1];
				}
			}
		} else {
			var arr = scene.split('_');
			if (arr.length == 2) {
				pid = arr[1];
			}
		}
	} else {
		pid = options.pid;
	}
	// 绑定上级
	if (pid) {
		if (uni.getStorageSync('token')) {
			getAjaxData('/api/xiluhouse/user/bind_recommend', {
				pid: pid
			});
		} else {
			app.globalData.pid = pid;
		}
	}
	typeof cb == 'function' && cb(id);
}

function getMapCenter(pointArray) {
	var sortedLongitudeArray = pointArray.map(item => item.longitude).sort(); //首先对经度进行排序，红色部分是array中经度的名称
	var sortedLatitudeArray = pointArray.map(item => item.latitude).sort(); //对纬度进行排序，红色部分是array中纬度的名称
	var centerLongitude = ((parseFloat(sortedLongitudeArray[0]) + parseFloat(sortedLongitudeArray[sortedLongitudeArray
		.length - 1])) / 2).toFixed(4);
	const centerLatitude = ((parseFloat(sortedLatitudeArray[0]) + parseFloat(sortedLatitudeArray[sortedLatitudeArray
		.length - 1])) / 2).toFixed(4);

	return [centerLongitude, centerLatitude];
}
// 拨打电话
function phoneCall(teldata) {
	if (!teldata.phoneNumber) {
		toast('未配置电话号码');
		return false;
	}
	// #ifdef APP-PLUS
	permissionSet.checkPermission('phoneCall', function() {
		uni.makePhoneCall(teldata);
	})
	return false;
	// #endif
	uni.makePhoneCall(teldata);
}
function removeTrailingZeros(num) {
    let numStr = num.toString();
    let i = numStr.length - 1;
    // 从后往前遍历，找到第一个不是 0 的位置
    while (i >= 0 && numStr[i] === '0') {
        i--;
    }
    // 如果当前位置是小数点，再往前移一位
    if (numStr[i] === '.') {
        i--;
    }
    // 截取字符串
    return numStr.slice(0, i + 1);
}


module.exports = {
	checkUpdate: checkUpdate,
	chooseImg: chooseImg,
	getAjaxList: getAjaxList,
	getAjaxData: getAjaxData,
	submitAjaxData: submitAjaxData,
	checkLogin: checkLogin,
	showError: showError,
	showSuccess: showSuccess,
	toast: toast,
	jumpPages: jumpPages,
	formatTime: formatTime,
	jumpToChat: jumpToChat,
	dotask: dotask,
	jumpAdvertTo: jumpAdvertTo,
	getMapCenter: getMapCenter,
	afterLogin: afterLogin,
	handlePid: handlePid,
	saveImages: saveImages,
	phoneCall: phoneCall,
	removeTrailingZeros:removeTrailingZeros,
};
